package com.tao.lab.bitmaprecycle;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Log;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @ProjectName: lab
 * @Package: com.tao.lab.bitmaprecycle
 * @ClassName: LruBitmapPool
 * @Description: java类作用描述
 * @Author: wangxf
 * @CreateDate: 2022/5/26 9:17
 * @UpdateUser: 更新者
 * @UpdateDate: 2022/5/26 9:17
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
class LruBitmapPool implements BitmapPool {
    private static final String TAG = "LruBitmapPool";
    private static final Bitmap.Config DEFAULT_CONFIG;
    private final LruPoolStrategy strategy;
    private final Set<Bitmap.Config> allowedConfigs;
    private final int initialMaxSize;
    private final LruBitmapPool.BitmapTracker tracker;
    private int maxSize;
    private int currentSize;
    private int hits;
    private int misses;
    private int puts;
    private int evictions;

    LruBitmapPool(int maxSize, LruPoolStrategy strategy, Set<Bitmap.Config> allowedConfigs) {
        this.initialMaxSize = maxSize;
        this.maxSize = maxSize;
        this.strategy = strategy;
        this.allowedConfigs = allowedConfigs;
        this.tracker = new LruBitmapPool.NullBitmapTracker();
    }

    public LruBitmapPool(int maxSize) {
        this(maxSize, getDefaultStrategy(), getDefaultAllowedConfigs());
    }

    public LruBitmapPool(int maxSize, Set<Bitmap.Config> allowedConfigs) {
        this(maxSize, getDefaultStrategy(), allowedConfigs);
    }

    public int getMaxSize() {
        return this.maxSize;
    }

    public synchronized void setSizeMultiplier(float sizeMultiplier) {
        this.maxSize = Math.round((float)this.initialMaxSize * sizeMultiplier);
        this.evict();
    }

    @SuppressLint("LogTagMismatch")
    public synchronized boolean put(Bitmap bitmap) {
        if (bitmap == null) {
            throw new NullPointerException("Bitmap must not be null");
        } else if (bitmap.isMutable() && this.strategy.getSize(bitmap) <= this.maxSize && this.allowedConfigs.contains(bitmap.getConfig())) {
            int size = this.strategy.getSize(bitmap);
            this.strategy.put(bitmap);
            this.tracker.add(bitmap);
            ++this.puts;
            this.currentSize += size;
            if (Log.isLoggable("LruBitmapPool", Log.ASSERT)) {
                Log.v("LruBitmapPool", "Put bitmap in pool=" + this.strategy.logBitmap(bitmap));
            }

            this.dump();
            this.evict();
            return true;
        } else {
            if (Log.isLoggable("LruBitmapPool", 2)) {
                Log.v("LruBitmapPool", "Reject bitmap from pool, bitmap: " + this.strategy.logBitmap(bitmap) + ", is mutable: " + bitmap.isMutable() + ", is allowed config: " + this.allowedConfigs.contains(bitmap.getConfig()));
            }

            return false;
        }
    }

    private void evict() {
        this.trimToSize(this.maxSize);
    }

    public synchronized Bitmap get(int width, int height, Bitmap.Config config) {
        Bitmap result = this.getDirty(width, height, config);
        if (result != null) {
            result.eraseColor(0);
        }

        return result;
    }

    @SuppressLint("LogTagMismatch")
    @TargetApi(12)
    public synchronized Bitmap getDirty(int width, int height, Bitmap.Config config) {
        Bitmap result = this.strategy.get(width, height, config != null ? config : DEFAULT_CONFIG);
        if (result == null) {
            if (Log.isLoggable("LruBitmapPool", Log.ASSERT)) {
                Log.d("LruBitmapPool", "Missing bitmap=" + this.strategy.logBitmap(width, height, config));
            }

            ++this.misses;
        } else {
            ++this.hits;
            this.currentSize -= this.strategy.getSize(result);
            this.tracker.remove(result);
            if (Build.VERSION.SDK_INT >= 12) {
                result.setHasAlpha(true);
            }
        }

        if (Log.isLoggable("LruBitmapPool", Log.ASSERT)) {
            Log.v("LruBitmapPool", "Get bitmap=" + this.strategy.logBitmap(width, height, config));
        }

        this.dump();
        return result;
    }

    @SuppressLint("LogTagMismatch")
    public void clearMemory() {
        if (Log.isLoggable("LruBitmapPool", Log.ASSERT)) {
            Log.d("LruBitmapPool", "clearMemory");
        }

        this.trimToSize(0);
    }

    @SuppressLint({"InlinedApi", "LogTagMismatch"})
    public void trimMemory(int level) {
        if (Log.isLoggable("LruBitmapPool", Log.ASSERT)) {
            Log.d("LruBitmapPool", "trimMemory, level=" + level);
        }

        if (level >= 60) {
            this.clearMemory();
        } else if (level >= 40) {
            this.trimToSize(this.maxSize / 2);
        }

    }

    @SuppressLint("LogTagMismatch")
    private synchronized void trimToSize(int size) {
        for(; this.currentSize > size; this.dump()) {
            Bitmap removed = this.strategy.removeLast();
            if (removed == null) {
                if (Log.isLoggable("LruBitmapPool", Log.ASSERT)) {
                    Log.w("LruBitmapPool", "Size mismatch, resetting");
                    this.dumpUnchecked();
                }

                this.currentSize = 0;
                return;
            }

            this.tracker.remove(removed);
            this.currentSize -= this.strategy.getSize(removed);
            removed.recycle();
            ++this.evictions;
            if (Log.isLoggable("LruBitmapPool", Log.ASSERT)) {
                Log.d("LruBitmapPool", "Evicting bitmap=" + this.strategy.logBitmap(removed));
            }
        }

    }

    private void dump() {
        if (Log.isLoggable("LruBitmapPool", Log.ASSERT)) {
            this.dumpUnchecked();
        }

    }

    private void dumpUnchecked() {
        Log.v("LruBitmapPool", "Hits=" + this.hits + ", misses=" + this.misses + ", puts=" + this.puts + ", evictions=" + this.evictions + ", currentSize=" + this.currentSize + ", maxSize=" + this.maxSize + "\nStrategy=" + this.strategy);
    }

    private static LruPoolStrategy getDefaultStrategy() {
        Object strategy;
        if (Build.VERSION.SDK_INT >= 19) {
            strategy = new SizeConfigStrategy();
        } else {
            strategy = new AttributeStrategy();
        }

        return (LruPoolStrategy)strategy;
    }

    private static Set<Bitmap.Config> getDefaultAllowedConfigs() {
        Set<Bitmap.Config> configs = new HashSet();
        configs.addAll(Arrays.asList(Bitmap.Config.values()));
        if (Build.VERSION.SDK_INT >= 19) {
            configs.add((Bitmap.Config) null);
        }

        return Collections.unmodifiableSet(configs);
    }

    static {
        DEFAULT_CONFIG = Bitmap.Config.ARGB_8888;
    }

    private static class NullBitmapTracker implements LruBitmapPool.BitmapTracker {
        private NullBitmapTracker() {
        }

        public void add(Bitmap bitmap) {
        }

        public void remove(Bitmap bitmap) {
        }
    }

    private static class ThrowingBitmapTracker implements LruBitmapPool.BitmapTracker {
        private final Set<Bitmap> bitmaps = Collections.synchronizedSet(new HashSet());

        private ThrowingBitmapTracker() {
        }

        public void add(Bitmap bitmap) {
            if (this.bitmaps.contains(bitmap)) {
                throw new IllegalStateException("Can't add already added bitmap: " + bitmap + " [" + bitmap.getWidth() + "x" + bitmap.getHeight() + "]");
            } else {
                this.bitmaps.add(bitmap);
            }
        }

        public void remove(Bitmap bitmap) {
            if (!this.bitmaps.contains(bitmap)) {
                throw new IllegalStateException("Cannot remove bitmap not in tracker");
            } else {
                this.bitmaps.remove(bitmap);
            }
        }
    }

    private interface BitmapTracker {
        void add(Bitmap var1);

        void remove(Bitmap var1);
    }
}
